import { createRouter, createWebHistory } from "vue-router";
import Model from "./model/index";
import dd from "dingtalk-jsapi";
const routes = [
  {
    //路由初始指向
    path: "/",
    redirect: "/supplierpro",
  },
  {
    //路由初始指向
    path: "/login",
    name: "login",
    component: () => import("@page/Basic/login/index.vue"),
  },
  {
    //注册页面
    path: "/register",
    name: "register",
    component: () => import("@page/Basic/register/index.vue"),
  },
  {
    //找回密码页面
    path: "/retrievepassword",
    name: "retrievepassword",
    component: () => import("@page/Basic/retrievepassword/index.vue"),
  },
  ...Model,
  {
    path: "/:pathMatch(.*)*",
    component: () => import("@page/Basic/lose/index.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

/**
 * 路由守卫
 * 处理钉钉环境下的权限验证
 */
router.beforeEach((to, from, next) => {
  console.log("路由导航:", to.path, "←", from.fullPath);

  // 如果启用了钉钉环境
  if (__DINGTALK__) {
    console.log("钉钉环境已启用");

    // 检查是否有 token（从 URL 参数或 sessionStorage）
    const tokenFromUrl = from.fullPath.split("?token=")[1];
    const tokenFromStorage = sessionStorage.getItem("token");
    const hasToken = !!tokenFromUrl || !!tokenFromStorage;

    // 检查钉钉环境
    const isInDingTalk = dd.env.platform !== "notInDingTalk";

    console.log("钉钉环境状态:", isInDingTalk ? "在钉钉内" : "在钉钉外");
    console.log("Token 状态:", hasToken ? "已存在" : "不存在");

    // 逻辑：在钉钉内 OR (在钉钉外 AND 有 token)
    if (isInDingTalk || hasToken) {
      console.log("✅ 路由守卫通过");
      next();
    } else {
      // 既不在钉钉内，也没有 token，需要重定向
      console.log("❌ 路由守卫失败，重定向到:", __REDIRECT__);
      if (__REDIRECT__) {
        window.location.href = __REDIRECT__;
      } else {
        next(); // 如果没有配置重定向地址，则放行
      }
    }
  } else {
    // 非钉钉环境，直接放行
    console.log("非钉钉环境，直接放行");
    next();
  }
});
export default router;
